package io.github.iogogogo.commons.util;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by tao.zeng on 2024/11/7.
 */
public class StreamUtils {

    private StreamUtils() {
    }

    private <T> T fun(Class<T> clz) {
        return null;
    }

    private <T extends Map<String, T>> T funMap(List<T> data) {
        return null;
    }

    /**
     * To map first val map.
     *
     * @param list      the list
     * @param fieldName the field name
     * @return the map
     */
    public static Map<String, ?> toMapGetFirstValue(List<?> list, String fieldName) {
        return toMap(list, fieldName, false);
    }

    /**
     * To map last val map.
     *
     * @param list      the list
     * @param fieldName the field name
     * @return the map
     */
    public static Map<String, ?> toMapGetLastValue(List<?> list, String fieldName) {
        return toMap(list, fieldName, true);
    }

    /**
     * To map map.
     *
     * @param list      the list
     * @param fieldName the field name
     * @param latest    the latest
     * @return the map
     */
    private static Map<String, ?> toMap(List<?> list, String fieldName, boolean latest) {
        return list.stream().collect(Collectors.toMap(x -> String.valueOf(ReflectUtils.getValue(x, fieldName)), x -> x, (m1, m2) -> latest ? m2 : m1));
    }

    /**
     * Group by map.
     *
     * @param list      the list
     * @param fieldName the field name
     * @return the map
     */
    public static Map<String, ? extends List<?>> groupBy(List<?> list, String fieldName) {
        return list.stream().collect(Collectors.groupingBy(x -> String.valueOf(ReflectUtils.getValue(x, fieldName))));
    }
}
